package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.common.RoleEnum;
import com.sqx.modules.health.entity.Check;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.entity.UserExpand;
import com.sqx.modules.health.service.ICheckService;
import com.sqx.modules.health.service.IUserExpandService;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.utils.MyBeanUtil;
import com.sqx.modules.health.vo.CheckVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-06-22
 */

@Slf4j
@Api(value = "", tags = "小程序人员审核接口", description = "")
@RestController
@RequestMapping("/health/check")
public class CheckController {
    @Autowired
    private ICheckService checkService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserExpandService expandService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新(提交审核信息)", notes = "新增或更新(提交审核信息)")
    public Result save(@RequestBody Check check) {
        if (ObjectUtil.isEmpty(check.getId())) {
            check.setCreatetime(LocalDateTime.now());
            check.setState("0");
            check.setRole(ObjectUtil.isEmpty(check.getRole()) ? RoleEnum.ROLE_H_NURSE.name() : check.getRole()); // 默认申请角色是护士
        }
        return Result.success(checkService.saveOrUpdate(check));
    }

    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public Result delete(@PathVariable Integer id) {
        return Result.success(checkService.removeById(id));
    }

    @GetMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
    public Result deleteBatch(@RequestParam List<Integer> ids) {
        return Result.success(checkService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部", notes = "查询全部")
    public Result findAll() {
        return Result.success(checkService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
    public Result findOne(@RequestParam Integer id) {
        return Result.success(checkService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") Long hid) {
        QueryWrapper<Check> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(hid)) {
            queryWrapper.eq("hid", hid);
        }
        queryWrapper.orderByDesc("id");
        Page<Check> page = checkService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<CheckVo> checkVos = MyBeanUtil.collectionCopy(page.getRecords(), CheckVo.class);
        checkVos.forEach(item -> {
            SysUserEntity user = userService.getRedisByUid(item.getInitiator());
            item.setNickName(user.getNickName());
            if (ObjectUtil.isNotEmpty(item.getAuditor())) {
                SysUserEntity auditor = userService.getRedisByUid(item.getAuditor());
                item.setAuditorName(ObjectUtil.isEmpty(auditor.getUsername()) ? auditor.getNickName() : auditor.getUsername());
            }
        });
        Page<CheckVo> result = new Page<>();
        result.setTotal(page.getTotal());
        result.setRecords(checkVos);
        return Result.success(result);
    }

    @GetMapping("/confirmCheck")
    private Result confirmCheck(@RequestParam Long id, @RequestParam Long auditor) {
        Check check = checkService.getById(id);
        check.setAuditor(auditor);
        check.setUpdatetime(LocalDateTime.now());
        check.setState("1");
        boolean editCheck = checkService.updateById(check);
        if (editCheck) {
            SysUserEntity user = userService.getById(check.getInitiator());
            user.setType(1);
            user.setUsername(check.getName());
            user.setPhone(check.getPhone());
            user.setRole(check.getRole());
            user.setPassword(check.getPassword());
            String flag = UUID.randomUUID().toString().replace("-", "");
            user.setExpandflag(flag);
            user.setHid(check.getHid());
            userService.saveOrUpdate(user);
            UserExpand userExpand = new UserExpand();
            userExpand.setUserflag(flag);
            userExpand.setMsgflag(0);
            expandService.saveOrUpdate(userExpand);
        } else {
            return Result.error(Constants.CODE_500, "error");
        }
        return Result.success("ok");
    }

}

